import React, { useEffect, useRef, useState } from 'react';
import { Form, message, Spin, Input } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
import { getBase64, isImg, isRAR, isVideo, uid } from '@/utils';
import { allGet } from '@/services/pc';
import { useForm } from 'antd/es/form/Form';
import ProcessBarUpload from '../../components/Upload/ProcessBarUpload';
import { InnerUpload } from '../../components/Upload';
import ZModal from '../../components/ZModal';
import { history, useHistory } from 'umi';
import { MessageType } from 'antd/lib/message';
import { apiUrl } from '@/common/const';

const UploadFm = ({
  className = '',
  size = 50,
  value = [],
  payload = {},
  action,
  name = 'file',
  tips = '点击上传',
  onBeforeUpload = async (file) => true,
  prefix = <i />,
  onChange = (value) => null,
  onSuccess = (fileList, file) => Promise.resolve(),
}) => {
  const [fileList, setFlieList] = useState<any[]>(value);
  const UploadRef = useRef<any>();

  const beforeUpload = async (file) => {
    if ((await onBeforeUpload?.(file)) === false) return false;

    // 尺寸不符合
    const isSizeOK = file.size < 1024 * 1024 * size;
    if (!isSizeOK) {
      message.error(`文件大小不能超过 ${size} Mb`);
      return false;
    }

    file.key = file?.uid || uid();
    file.url = await getBase64(file);
    // fileListCount.current++;
    return file;
  };
  const handleUploadChange = async (fileList) => {
    const newFileList = [fileList[fileList.length - 1]];
    setFlieList(newFileList);
    onChange?.(newFileList);
  };
  const handleSuccess = async (fileList, file) => {
    onSuccess?.(fileList, file);
  };

  const upLoadProps = {
    fileList,
    onChange: handleUploadChange,
    name,
    action,
    multiple: false,
    data: () => payload,
    beforeUpload: beforeUpload,
    onSuccess: handleSuccess,
  };

  const statusInfo = () => {
    const file = fileList[fileList.length - 1];
    if (file?.status === 'done') {
      return { text: `已上传成功，点击可重新上传 （${file.name}）`, ...file };
    }
    if (file?.status === 'uploading') {
      return { text: `${file.name} 上传中...`, ...file };
    }
    if (file?.status === 'error') {
      return { text: '上传失败，请重新上传', ...file };
    }
    return { text: tips, status: 'none' };
  };
  const info = statusInfo();
  return (
    <div className={classNames(styles.uploadfm, className)}>
      <InnerUpload ref={UploadRef} {...(upLoadProps as any)} disabled={info.status === 'uploading'}>
        <div className={classNames(styles.left, styles[info.status])}>
          {info.url && <i className={styles.img} style={{ backgroundImage: `url(${info.url})` }} />}

          {info.status === 'none' && <div className={styles.button}>上传封面</div>}
          {(info.status === 'done' || info.status === 'error') && (
            <div className={styles.footer}>
              {info.status === 'error' && <span className={styles.errortext}>上传失败</span>}
              <div className={styles.button}>上传封面</div>
            </div>
          )}
          {info.status === 'uploading' && <Spin spinning />}
        </div>
      </InnerUpload>
      <div className={styles.right}>建议尺寸：490*276px 格式：jpg / png / gif</div>
      {/* <div onClick={handleCancel}>222</div> */}
    </div>
  );
};

const Index = () => {
  const [config, setConfig] = useState<any>({});
  const { lid, bid, classid } = (useHistory().location as any)?.query;
  const init = async () => {
    const response = await allGet({ params: { mod: 'teacher', do: 'add', version: 'pc1.0' } });
    setConfig(response);
  };
  const { location } = useHistory();
  useEffect(() => {
    init();
  }, []);
  const uploadPayload = {
    mod: 'swfupload',
    ac: 'busywork',
    version: 'pc1.0',
    lid,
    bid,
    uid: config?.data?.space?.uid,
    hash: config?.data?.swfconfig?.hash,
  };

  const handleWorkBeforeUpload = async (file) => {
    if (!isVideo(file.name) && !isImg(file.name)) {
      message.error('图片仅支持 jpg/png/gif 格式, 视频仅支持 avi/mp4/mov 格式');
      return false;
    }
    return true;
  };
  const handleFmBeforeUpload = async (file) => {
    if (!isImg(file.name)) {
      message.error('图片仅支持 jpg/png/gif 格式');
      return false;
    }
    return true;
  };
  const handleYjBeforeUpload = async (file) => {
    if (!isRAR(file.name)) {
      message.error('仅支持 zip/rar');
      return false;
    }
    return true;
  };

  const validUpload = (rule, value: any, required = true, message = '') => {
    if (required && !value) return Promise.reject(`请上传${message}`);

    if (Array.isArray(value)) {
      if (value.some((item) => item?.status === 'uploading')) {
        return Promise.reject(`还有正在上传的${message}，稍等一下`);
      }
      if (value.some((item) => item?.status === 'error')) {
        return Promise.reject(`有上传失败的${message}，请重新上传`);
      }
    }
    return Promise.resolve();
  };

  const zModalRef = useRef<any>();
  const handleBack = () => {
    if (location?.query?.redirect) {
      history.replace(window.decodeURIComponent(location?.query?.redirect));
      return;
    }
    history.goBack();
  };
  const [submitLoading, setSubmitLoading] = useState(false);
  const handleSubmit = async () => {
    try {
      await form.validateFields();
      // if (!uploadwork.current.url && uploadwork.current.type === 'video') {
      //   return message.info('视频上传中，请稍等...', 0);
      // }
      if (submitLoading) return;
      setSubmitLoading(true);
      const params = {
        version: 'pc1.0',
        mod: 'busywork',
        do: 'post',
        action: 'upload',
        type: 'busywork',
        lid,
        bid,
        subject: form.getFieldValue('subject'),
        worksubmit: 1,
        thumb: uploadfm.current.url,
        file: uploadyj.current.url,
      } as any;
      if (uploadwork.current.type === 'video') {
        params.video = uploadwork.current.url;
        params.videoid = uploadwork.current.videoId;
      } else {
        params.pic = uploadwork.current.url;
      }
      const response = await allGet({
        params,
      });
      if (response.success) {
        zModalRef.current = ZModal.success({
          title: '作业上传成功',
          quickClose: false,
          closeable: false,
          content: (
            <div className={styles.modalBottons}>
              <div
                className={classNames(styles.button, styles.primary)}
                onClick={() => {
                  zModalRef.current?.close?.();
                  history.push('/learning?index=2');
                }}
              >
                前往查看作业
              </div>
              <div
                className={styles.button}
                onClick={() => {
                  zModalRef.current?.close?.();
                  history.push('/');
                }}
              >
                返回首页
              </div>
            </div>
          ),
        });
      }
      setSubmitLoading(false);
    } catch (error) {}
  };

  const uploadwork = useRef<any>({});
  const ecodeViedo = useRef(false);
  const uploadVideo2PhpTimer = useRef<any>();
  useEffect(() => {
    return () => {
      clearTimeout(uploadVideo2PhpTimer.current);
    };
  });
  const uploadVideo2Php = async (file) => {
    if (ecodeViedo.current === false) {
      // message.loading({
      //   content: '视频上传中，请稍等...',
      //   key: 'messageA',
      //   duration: 0,
      // });
    }
    ecodeViedo.current = true;
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'video',
        do: 'aliyun',
        action: 'upload',
        type: 'busywork',
        field: 'video',
        aid: file.aid || 0,
        lid,
        bid,
        filename: file.name,
        videoid: file.videoId,
      },
    });
    if (!response.success) {
      ecodeViedo.current = false;
      message.destroy('messageA');
    }
    if (response.success && response.data.attachment) {
      clearInterval(uploadVideo2PhpTimer.current);
      file.attachment = response.data.attachment;
      uploadwork.current = {
        type: 'video',
        url: response.data.attachment,
        videoId: file.videoId,
        name: file.name,
      };
      ecodeViedo.current = false;
      message.destroy();
    }
    /**
     * php 说
     * 如果 data.attachment==''刚做轮询，一直到data.attachment不为空
     */
    if (response.success && !response.data.attachment && response.data?.attachid) {
      file.aid = response.data?.attachid;
      uploadVideo2PhpTimer.current = setTimeout(() => {
        uploadVideo2Php(file);
      }, 1000);
    }
  };
  // 上传阿里云视频成功，视频要单独处理
  const handleUploadWorkSuccess = async (file) => {
    if (isVideo(file.name)) {
      file.videoId = file?.response?.videoId;
      uploadwork.current = {
        type: 'video',
        videoId: file.videoId,
        name: file.name,
      };
      uploadVideo2Php(file);
    } else {
      const { response = {} } = file;
      uploadwork.current = {
        type: 'img',
        url: response.data.attachment,
        name: file.name,
      };
    }
  };

  const uploadfm = useRef<any>({});
  const handleUploadFmSuccess = async (file) => {
    const { response = {} } = file;
    uploadfm.current = {
      url: response.data.attachment,
      name: file.name,
    };
  };
  const uploadyj = useRef<any>({});
  const handleUploadYjSuccess = async (file) => {
    const { response = {} } = file;
    uploadyj.current = {
      url: response.data.attachment,
      name: file.name,
    };
  };

  const [loading, setLoading] = useState(true);
  // 作业详情
  const [worksDetail, setWorksDetail] = useState({});
  const [initialValues, setInitialValues] = useState({});
  const getWorksDetail = async () => {
    if (!bid) {
      return setLoading(false);
    }
    const data = await allGet({ params: { mod: 'busywork', do: 'post', bid, version: 'pc1.0' } });
    const item = data?.work || {};
    uploadwork.current = {
      type: item.video ? 'video' : 'img',
      name: item.subject,
      url: item.video || item.pic,
      videoId: item.videoid,
    };
    uploadfm.current = {
      url: item?.thumb,
    };
    uploadyj.current = {
      url: item.file,
      name: item.file,
    };
    const values = {
      work: [
        {
          url: item.video || item.pic,
          name: item.subject,
          uid: item.video || item.pic,
          status: 'done',
        },
      ],
      fm: [
        {
          url: item?.thumbshow,
          name: item?.thumb,
          uid: item?.thumb,
          status: 'done',
        },
      ],
      subject: item?.subject,
    } as any;
    if (item.file) {
      values.yj = [
        {
          url: item.file,
          name: item.file,
          uid: item.file,
          status: 'done',
        },
      ];
    }
    setInitialValues(values);
    setWorksDetail(data.data || {});
    setLoading(false);
  };
  useEffect(() => {
    getWorksDetail();
  }, []);

  const [form] = useForm();
  return (
    <div className={styles.page}>
      <div className={styles.title}>{bid ? '编辑作业' : '上传作业'}</div>
      <div className={styles.main}>
        {!loading && (
          <Form
            form={form}
            scrollToFirstError
            className={styles.form}
            layout="vertical"
            name="basic"
            autoComplete="off"
            initialValues={initialValues}
            validateTrigger={false}
          >
            <Form.Item
              label={
                <div>
                  上传作业：
                  <span className={styles.tips}>
                    （作业不能超过200mb，建议1280*720以上，支持格式：avi / mp4 / mov / jpg / png /
                    gif 格式）
                  </span>
                </div>
              }
              name="work"
              rules={[{ validator: (rule, value) => validUpload(rule, value, true, '作业') }]}
            >
              <ProcessBarUpload
                prefix={<i className={styles.iconfile} />}
                tips="点击上传"
                onBeforeUpload={handleWorkBeforeUpload}
                action={apiUrl}
                name="Filedata"
                size={200}
                payload={{ ...uploadPayload, field: 'pic' }}
                aliyunAuthPayload={{ classid, type: 'busywork' }}
                onSuccess={(_, file) => handleUploadWorkSuccess(file)}
              />
            </Form.Item>
            <Form.Item
              label="作业标题"
              name="subject"
              required={false}
              rules={[{ required: true, message: '请输入作业标题' }]}
            >
              <Input placeholder="请输入" className={styles.input} />
            </Form.Item>
            <Form.Item
              label="作业封面"
              name="fm"
              rules={[{ validator: (rule, value) => validUpload(rule, value, true, '作业封面') }]}
            >
              <UploadFm
                onBeforeUpload={handleFmBeforeUpload}
                action={apiUrl}
                name="Filedata"
                payload={{ ...uploadPayload, field: 'thumb' }}
                onSuccess={(_, file) => handleUploadFmSuccess(file)}
              />
            </Form.Item>
            <Form.Item
              label="源文件"
              name="yj"
              rules={[{ validator: (rule, value) => validUpload(rule, value, false, '源文件') }]}
            >
              <ProcessBarUpload
                className={styles.yj}
                prefix={<i className={styles.iconfj} />}
                tips="上传作品源文件压缩包（zip，rar）"
                onBeforeUpload={handleYjBeforeUpload}
                action={apiUrl}
                name="Filedata"
                payload={{ ...uploadPayload, field: 'file' }}
                onSuccess={(_, file) => handleUploadYjSuccess(file)}
              />
            </Form.Item>
          </Form>
        )}
        <div className={styles.footer}>
          <div className={styles.submit} onClick={handleSubmit}>
            发布作业
          </div>
          <div className={styles.back} onClick={handleBack}>
            返回
          </div>
        </div>
      </div>
    </div>
  );
};

export default Index;
